package gl.android.jxzs;

import gl.adapter.TitieBarAdapter;
import gl.android.biyiqing.R;
import gl.common.BaseControl;
import gl.common.UserManger;
import gl.uitls.Lg;
import net.tsz.afinal.http.AjaxCallBack;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;

/**
 * A simple {@link android.support.v4.app.Fragment} subclass.
 * 
 */
@SuppressLint("SetJavaScriptEnabled")
public class HtmlFragment extends Fragment {
	public static final int WEB = 1;
	public String url;
	public String title;
	public String createTime;
	/**
	 * 仅仅只需要显示文本
	 */
	public boolean isText;
	private int mediatype;

	public HtmlFragment(String url, String title) {
		this.url = url;
		this.title = title;
	}

	public HtmlFragment(String url, String title, int mediatype) {
		this.url = url;
		this.title = title;
		this.mediatype = mediatype;
	}

	public HtmlFragment(boolean isText, String url, String title) {
		this.url = url;
		this.isText = isText;
		this.title = title;
	}

	WebView webView;
	View loadtip;
	Handler handler = new Handler();

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_html, container, false);
		webView = (WebView) view.findViewById(R.id.tv_nick);
		loadtip = view.findViewById(R.id.loadtip);
		webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
		webView.getSettings().setJavaScriptEnabled(true);
		loadtip.setVisibility(View.GONE);
		webView.setWebViewClient(new WebViewClient() {
			@Override
			@Deprecated
			public void onTooManyRedirects(WebView view, Message cancelMsg,
					Message continueMsg) {
				super.onTooManyRedirects(view, cancelMsg, continueMsg);
			}

			@Override
			public void onReceivedError(WebView view, int errorCode,
					String description, String failingUrl) {
				setHTMLText(errorCode + ",网络错误,请联系管理员");
			}

			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) { // 重写此方法表明点击网页里面的链接还是在当前的webview里跳转，不跳到浏览器那边
				Lg.i(this, "shouldOverrideUrlLoading:" + url);
				view.loadUrl(url);
				return true;
			}

			@Override
			public void onReceivedSslError(WebView view,
					SslErrorHandler handler, android.net.http.SslError error) { // 重写此方法可以让webview处理https请求
				handler.proceed();
			}

			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				super.onPageStarted(view, url, favicon);
				Lg.i(this, "onPageStarted" + url);
				loadtip.setVisibility(View.GONE);
				handler.postDelayed(new Runnable() {

					@Override
					public void run() {
						loadtip.setVisibility(View.VISIBLE);
					}
				}, 30 * 1000);
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
				loadtip.setVisibility(View.GONE);
				handler.removeCallbacksAndMessages(null);
				Lg.i(this, "onPageFinished");
			}
		});

		// 设置WebChromeClient
		webView.setWebChromeClient(new WebChromeClient() {
			// 处理javascript中的alert
			@Override
			public boolean onJsAlert(WebView view, String url, String message,
					final JsResult result) {
				// 构架一个builder来显示网页中的对话框
				Builder builder = new Builder(view.getContext());
				builder.setTitle("提示对话框");
				builder.setMessage(message);
				builder.setPositiveButton(android.R.string.ok,
						new AlertDialog.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// 点击确定按钮之后，继续执行网页中的操作
								result.confirm();
							}
						});
				builder.setCancelable(false);
				builder.create();
				builder.show();
				return true;
			}
		});

		getdata();
		initTitleBar(title);

		return view;
	}

	private void initTitleBar(String title) {
		if (getActivity() instanceof TitieBarAdapter) {
			TitieBarAdapter mTitieBarAdapter = (TitieBarAdapter) getActivity();
			mTitieBarAdapter.getBarView().menu
					.setOnClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {

						}
					});
			if (isText) {
				mTitieBarAdapter.getBarView().back
						.setOnClickListener(new View.OnClickListener() {
							@Override
							public void onClick(View v) {
								getActivity().onBackPressed();
							}
						});
			}

			mTitieBarAdapter.getBarView().title.setText("" + title);
			mTitieBarAdapter.getBarView().menu.setVisibility(View.GONE);
		}

	}

	private void getdata() {
		if (isText) {
			setHTMLText(url);
			initTitleBar(title);
			return;
		}
		if (mediatype == WEB) {
			if (!TextUtils.isEmpty(url)) {
				setHTMLURL("http://"
						+ url
						+ String.format("?name=%s&userpsw=%s",
								UserManger.getInstance().username,
								UserManger.getInstance().password));
			}
			initTitleBar(title);
			return;
		}
		BaseControl.get(url, new AjaxCallBack<String>() {
			@Override
			public void onStart() {
				super.onStart();
				setHTMLText("正在加载");
			}

			@Override
			public void onSuccess(String t) {
				super.onSuccess(t);
				if (TextUtils.isEmpty(t)) {
					setHTMLText("没有内容");
				}
				else
					setHTMLText(t);
			}

			@Override
			public void onFailure(Throwable t, int errorNo, String strMsg) {
				super.onFailure(t, errorNo, strMsg);
			}
		});
	}

	private void setHTMLText(String t) {
		if (!TextUtils.isEmpty(t) && t.startsWith("http")) {
			setHTMLURL(t);
		}
		else {
			webView.loadDataWithBaseURL("", t + "", "text/html", "UTF-8", null);
		}

	}

	private void setHTMLURL(String t) {
		@SuppressWarnings("deprecation")
		RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
				RelativeLayout.LayoutParams.FILL_PARENT,
				RelativeLayout.LayoutParams.WRAP_CONTENT);
		layoutParams.setMargins(1, 0, 1, 0);
		webView.setLayoutParams(layoutParams);
		webView.loadUrl(t);
	}
}
